<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>用户管理</title>
		<script src="../jss/global.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<div class="layui-form-item" style="margin-top: 20px;" onsubmit="return false;">
			<form class="layui-form">
				<label class="layui-form-label">用户名:</label>
				<div class="layui-input-inline" style="width:120px;">
					<input type="text" id="sname" name="userName" autocomplete="off" class="layui-input">
				</div>

				<label class="layui-form-label">用户手机号:</label>
				<div class="layui-input-inline" style="width:120px;">
					<input type="text" id="sphone" name="userPhone" autocomplete="off" class="layui-input">
				</div>

				<label class="layui-form-mid">是否锁定:</label>
				<div class="layui-input-inline" style="width:120px;">
					<select id="slock" name="isLockout">
						<option value="">请选择</option>
						<option value="1">已锁定</option>
						<option value="0">未锁定</option>
					</select>
				</div>

			</form>
			<button class="layui-btn" id="search" data-type="reload">搜索</button>
		</div>

		<!--数据表格-->
		<table class="layui-hide" id="demo" lay-filter="test"></table>
		<!--顶部工具栏-->
		<script type="text/html" id="topToolbar">
			<div class="layui-btn-container">
				<button class="layui-btn layui-btn-sm" lay-event="createUser">创建用户</button>
			</div>
		</script>

		<!--行内工具栏-->
		<script type="text/html" id="barDemo">
			<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="setRole">角色</a>
			<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="resetPwd">密码重置</a>
			<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
			<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		</script>

		<!-- 添加页面开始 -->
		<form class="layui-form" onsubmit="return false;" id="addForm" style="display: none;">

			<div class="layui-form-item">
				<label class="layui-form-label">用户名：</label> <input type="text" name="userName" style="width: 130px" lay-verify="required" placeholder="请输入学号" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">登录密码：</label> <input type="text" name="userPassword" style="width: 130px" placeholder="请输入卡号" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">邮箱：</label> <input type="text" name="userEmail" style="width: 130px" placeholder="请输入姓名" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">手机号：</label> <input type="text" name="userPhone" style="width: 130px" placeholder="请输入备注" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn" lay-submit lay-filter="addS">添加</button>
					<button type="reset" class="layui-btn layui-btn-primary">重置</button>
				</div>
			</div>

		</form>
		<!-- 添加页面结束 -->
		<!-- 修改页面开始 -->
		<form class="layui-form" onsubmit="return false;" id="upForm" style="display: none;">
			<div class="layui-form-item" style="display: none;">
				<label class="layui-form-label">用户Id：</label> <input type="text" name="userId" id="upId" style="width: 130px" lay-verify="required" placeholder="请输入学号" autocomplete="off" class="layui-input">
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">用户名：</label> <input type="text" name="userName" id="upName" style="width: 130px" lay-verify="required" placeholder="请输入学号" autocomplete="off" class="layui-input" readonly="readonly">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">登录密码：</label> <input type="text" name="userPassword" id="upPassword" style="width: 130px" placeholder="请输入卡号" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">邮箱：</label> <input type="text" name="userEmail" id="upEmail" style="width: 130px" placeholder="请输入姓名" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">手机号：</label> <input type="text" name="userPhone" id="upPhone" style="width: 130px" placeholder="请输入备注" autocomplete="off" class="layui-input">
			</div>

			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn" lay-submit lay-filter="update">修改</button>
				</div>
			</div>

		</form>
		<!-- 修改页面结束 -->




		<!--穿梭框-->
		<div id="yh_role" style="display:none">
			<div id="role_transfer" class="demo-transfer"></div>

		</div>

		<!-- 锁定状态分析逻辑 -->
		<script type="text/html" id="state">

			{{#      if(d.isLockout == 0){       }}
			<input type="checkbox" name="switch" lay-skin="switch" data-id="{{d.userId}}" lay-text="已启用|已锁定" value="0" lay-filter="switch" checked="checked"> {{#       } else {       }}
			<input type="checkbox" name="switch" lay-skin="switch" data-id="{{d.userId}}" lay-text="已启用|已锁定" value="1" lay-filter="switch"> {{#        }              }}

		</script>

		<script>
			var addIndex;
			layui.use(['laydate', 'layer', 'table', 'form', 'transfer', 'laytpl'], function() {
				var laydate = layui.laydate,
					layer = layui.layer,
					table = layui.table,
					form = layui.form,
					$ = layui.$,
					laytpl = layui.laytpl,
					transfer = layui.transfer;

				//执行一个 table 实例
				table.render({
					elem: '#demo',
					height: 400,
					toolbar: '#topToolbar',
					url: globalData.server + "user/select",
					where: {
						token: globalData.getToken
					},
					title: '用户表',
					page: true,
					cols: [
						[{
							type: 'checkbox'
						}, {
							field: 'userId',
							title: '用户id',
							width: 100,
							hide: true
						}, {
							field: 'userImg',
							title: '头像',
							width: 100
						}, {
							field: 'userName',
							title: '登录名',
							width: 100
						}, {
							field: 'userPassword',
							title: '登录密码',
							width: 100,
							hide: true
						}, {
							field: 'userEmail',
							title: '邮箱',
							width: 100
						}, {
							field: 'userPhone',
							title: '手机号',
							width: 100,
						}, {
							field: 'isLockout',
							title: '是否锁定',
							width: 100,
							templet: '#state'
						}, {
							field: 'userCreateTime',
							title: '账户创建时间',
							width: 100
						}, {
							field: 'userLastLoginTime',
							title: '最新登录时间',
							width: 100
						}, {
							field: 'userPsdWrong',
							title: '密码错误次数',
							width: 100
						}, {
							field: 'userLockTime',
							title: '锁定时间',
							width: 100
						}, {
							title: '操作',
							width: 260,
							fixed: 'right',
							toolbar: '#barDemo'
						}]
					],
					id: "testTable",
				});
				//数据重载

				//点击搜索按钮，调用方法
				$('#search').click(function() {
					table.reload('testTable', {
						where: {
							//模糊查询的条件
							'userName': $('#sname').val(),
							'userPhone': $('#sphone').val(),
							'isLockout': $('#slock').val(),
						}
					});

				});

				//点击添加按钮弹出页面
				table.on('toolbar(test)', function(obj) {
					switch(obj.event) {
						case 'createUser':
							{
								addIndex = layer.open({
									type: 1,
									content: $('#addForm'),
									area: ['600px', '500px'],
									title: "您正在添加用户"
								});
							}
							break;
					};
				});

				//监听表单提交--添加
				form.on('submit(addS)', function(data) {
					//将表单以序列化提交
					var data = $("#addForm").serialize() + "&token=" + globalData.getToken();
					//提交  ajax
					$.post(
						//地址
						globalData.server + 'user/create',
						data,
						//整个表单的数据以序列化的形式提交
						function(res) {
							if(res.code == 2) {
								layer.msg(res.msg, {
									icon: 4
								}, function() {
									layer.close(addIndex); //关闭添加窗口
									window.location.reload(); //刷新页面
								});
							} else if(res.code == 0) {
								layer.msg(res.msg, {
									icon: 1
								}, function() {
									layer.close(addIndex); //关闭添加窗口
									window.location.reload(); //刷新页面
								});
							} else {
								layer.msg(res.msg, {
									icon: 4
								}, function() {
									layer.close(addIndex); //关闭添加窗口
									window.location.reload(); //刷新页面
								});
							}

						}, 'json');
				});

				//监听工具条
				table.on('tool(test)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
					var data = obj.data; //获得当前行数据    data.列名
					var layEvent = obj.event; //获得 lay-event 对应的值
					var tr = obj.tr; //获得当前行 tr 的DOM对象

					if(layEvent === 'del') { //删除
						layer.confirm("真的删除用户：" + data.userName + "吗？",
							function(index) {
								if(data.userId == globalData.getLoginUid()) {
									obj.del();
									//删除对应行（tr）的DOM结构，并更新缓存
									layer.close(index);
									//向服务端发送删除指令							
									$.post(
										//地址
										globalData.server + 'user/delete', //删除
										{
											token: globalData.getToken(),
											'uid': data.userId
										},
										function(res) {
											if(res.code == 0) {
												layer.msg('删除成功', {
													icon: 1
												});
											} else {
												layer.msg('删除失败', {
													icon: 4
												});
											}
										}, 'json');
								} else {
									layer.msg(' 阿sir，你不能自己删自己啊', {
										icon: 4
									}, function() {
										layer.close(index);
									});
								}

							});
					} else if(layEvent === 'edit') { //编辑
						//do something
						//弹出一个修改的页面
						//数据回显
						$('#upId').val(data.userId);
						$('#upName').val(data.userName);
						$('#upPassword').val(data.userPassword);
						$('#upPhone').val(data.userPhone);
						$('#upEmail').val(data.userEmail);
						layer.open({
							type: 1,
							content: $('#upForm'),
							area: ['600px', '500px'],
							title: ["正在修改" + data.userName + "的信息"]
						});
						//同步更新缓存对应的值
						obj.update({
							username: '123',
							title: '正在更新'
						});
					} else if(layEvent === 'resetPwd') { //编辑																		
						layer.confirm("确定要重置用户：" + data.userName + "的密码？", function(index) {
							layer.close(index);
							$.post(
								//地址
								globalData.server + 'user/resetPwd', //删除
								{
									token: globalData.getToken(),
									'userId': data.userId
								},
								function(res) {
									if(res.code == 0) {
										layer.msg(res.msg, {
											icon: 1
										});

									} else {
										layer.msg(res.msg, {
											icon: 4
										});
									}
								}, 'json');

						});

					} else if(layEvent === 'setRole') { //设置角色
						//弹出角色设置框	 
						layer.open({
							type: 1,
							title: '您正在设置用户[' + data.userName + ']的角色',
							content: $("#yh_role"),
							area: ['500px', '400px'],
							fixed: false, //不固定
							maxmin: true,
							offset: '10px'
						});
						//左侧数据
						$.post("" + globalData.server + "user/GetRolesAll", {
								"token": globalData.getToken
							}, function(result) {
								//遍历result,替换key
								var rul = result.map(function(item) {
									return {
										value: item.roleId,
										title: item.roleName
									}
								});
								var rdata = new Array();
								//右侧角色
								$.post("" + globalData.server + "user/getRolesByUid", {
									"uid": data.userId,
									"token": globalData.getToken
								}, function(result) {
									if(result.count > 0) {
										for(var i = 0; i < result.data.length; i++) {
											rdata.push(result.data[i].roleId);
										}
									}
									//数据穿梭
									transfer.render({
										elem: '#role_transfer',
										title: ['系统所有角色', '当前用户的角色'],
										data: rul,
										value: rdata,
										onchange: function(obj, index) {
											if(index == "0") {
												//设置用户角色
												for(var i = 0; i < obj.length; i++) {
													$.post("" + globalData.server + "user/addUserRole", {
														"userId": data.userId,
														"roleId": obj[i].value,
														"token": globalData.getToken()
													}, function(result) {

													}, "json");
												}

											} else {
												//删除用户角色
												for(var i = 0; i < obj.length; i++) {
													$.post("" + globalData.server + "user/delUserRole", {
														"userId": data.userId,
														"roleId": obj[i].value,
														"token": globalData.getToken()
													}, function(result) {

													}, "json");
												}

											}
										}
									});
								}, "json");
							},
							"json");

					}

				});

				//监听表单提交--修改
				form.on('submit(update)', function(data) {
					var data = $("#upForm").serialize() + "&token=" + globalData.getToken();
					//将表单以序列化提交
					//提交  ajax
					$.post(
						//地址
						globalData.server + 'user/update', //修改用户的方法
						data,
						function(res) {
							if(res.code == 0) {
								layer.msg('修改成功', {
									icon: 1
								}, function() {
									layer.close(addIndex); //关闭修改窗口
									window.location.reload(); //刷新页面
								});
							} else {
								layer.msg('修改失败，请刷新重试', {
									icon: 4
								}, function() {
									layer.close(addIndex); //关闭修改窗口
									window.location.reload(); //刷新页面
								});
							}
						}, 'json');
				});

				//监听开关事件
				form.on('switch(switch)', function(data) {
					//console.log(data.elem); //得到checkbox原始DOM对象
					//console.log(data.elem.checked); //开关是否开启，true或者false
					//console.log(data.value); //开关value值，也可以通过data.elem.value得到
					//console.log(data.othis); //得到美化后的DOM对象
					var id = $(this).attr('data-id');
					var ck = data.elem.checked;

					layer.confirm(ck ? '确定启用？' : '确定禁用？', {
						btn1: function(index) { //点击确定
							if(id == globalData.getLoginUid()) {
								//将表单以序列化提交
								//提交  ajax
								$.post(
									//地址
									globalData.server + 'user/lockUser', //锁定用户的方法
									{ //将数据以序列化提交
										token: globalData.getToken(),
										'isLockout': data.value,
										'userId': id

									},
									function(res) {
										if(res.code == 0) {
											layer.msg(res.msg, {
												icon: 1
											}, function() {
												layer.close(index);
											});
										} else if(res.code == 1) {
											layer.msg(res.msg, {
												icon: 1
											}, function() {
												layer.close(index);
											});
										} else {
											layer.msg(res.msg, {
												icon: 4
											}, function() {
												data.elem.checked = !ck;
												layer.close(index);
												form.render('checkbox');
											});
										}
									}, 'json');

							} else {
								layer.msg("你不能着自己锁自己", {
									icon: 4
								}, function() {
									data.elem.checked = !ck;
									layer.close(index);
									form.render('checkbox');
								});
							}
						},
						btn2: function() { //点击取消
							data.elem.checked = !ck;
							form.render('checkbox');
							
						},
						cancel: function() { //点击X号
							data.elem.checked = !ck;
							form.render('checkbox');
						},
					});

				});

			});
		</script>

	</body>

</html>